package com.ljl.mvvmdemo.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.ljl.mvvmdemo.db.entity.Login
import com.ljl.mvvmdemo.db.getAppDataBase
import com.ljl.mvvmdemo.net.ApiService
import com.ljl.mvvmdemo.net.HttpConstants
import com.ljl.mvvmdemo.net.HttpConstants.environment
import com.ljl.mvvmdemo.net.NetManageDispatch
import com.ljl.mvvmdemo.util.GlobalDataHelper
import com.ljl.mvvmdemo.util.loge
import kotlinx.coroutines.launch

/**
 * created by luojialun on 2024/4/10
 */
class MainViewModel : BaseViewModel() {

    fun jump() {
        //startActivity(SecondActivity::class.java)

        showLoading(GlobalDataHelper.getInstance().getLogin().system_book_code)
    }

    fun showLoadingTip() {
        showLoading("提示")
    }

    fun insert() {
        viewModelScope.launch {
            val login = Login(system_book_code = "2072", system_book_name = "熟食", branch_num = 1, branch_name = "门店1")
            getAppDataBase().getLoginDao().insertLogin(login)
        }
    }

    fun query() {
        /*viewModelScope.launch {
            val student = getAppDataBase().getStudentDao().getStudentByNo(1)
            val json = Gson().toJson(student)
            Log.e("TAG", "json:$json")
        }*/
        viewModelScope.launch {
            val result = try {
                Result.success(NetManageDispatch.getInstance().create(ApiService::class.java).getKey("99676"))
            } catch (e: Exception) {
                Result.failure(e)
            }
            Log.e("TAG", result.getOrNull().toString())

        }

    }

    fun request() {
/*        viewModelScope.launch {
*//*             val result = try {
                 Result.success(NetManageDispatch.getInstance().create(ApiService::class.java).getSystemBookProxy("99676"))
             } catch (e: Exception) {
                 Result.failure(e)
             }

              val systemBookProxy = result.getOrNull()?.data?.systemBookProxy

             HttpConstants.initUrl(systemBookProxy)*//*

            kotlin.runCatching {
                NetManageDispatch.getInstance().create(ApiService::class.java).getSystemBookProxy("99676")
            }.onSuccess {
                val systemBookProxy = it.data.systemBookProxy
                HttpConstants.initUrl(systemBookProxy)
            }.onFailure {
                loge(it.toString())
            }

        }*/

        requestOnUI({ NetManageDispatch.getInstance().create(ApiService::class.java).getSystemBookProxy("1212199679") }, {
            val systemBookProxy = it?.systemBookProxy
            loge(Gson().toJson(systemBookProxy))
            HttpConstants.initUrl(systemBookProxy, environment)
        }, { code, msg ->
            loge("$code $msg")
        }, {
            loge(it.toString())
        }, true)
    }


}